package com.qys.livesMall.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.cache.utils.CacheUtil;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.bean.BeanProUtils;
import com.qys.livesMall.system.source.domain.dto.menu.MenuSearch;
import com.qys.livesMall.system.source.domain.entity.SysMenu;
import com.qys.livesMall.system.source.domain.vo.menu.TreeSelect;
import com.qys.livesMall.system.source.domain.vo.menu.MenuVO;
import com.qys.livesMall.system.source.mapper.SysMenuMapper;
import com.qys.livesMall.system.source.service.ISysMenuService;
import com.qys.livesMall.user.constants.UserConstants;
import com.qys.livesMall.user.domain.dto.role.EditRoleMenu;
import com.qys.livesMall.user.domain.entity.SysRole;
import com.qys.livesMall.user.domain.entity.SysRoleMenu;
import com.qys.livesMall.user.domain.entity.SysUser;
import com.qys.livesMall.user.domain.vo.role.RoleMenuTree;
import com.qys.livesMall.user.mapper.SysRoleMapper;
import com.qys.livesMall.user.mapper.SysRoleMenuMapper;
import com.qys.livesMall.user.service.ISysRoleMenuService;
import com.qys.livesMall.user.service.ISysUserService;
import com.qys.livesMall.framework.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 菜单 业务层处理
 *
 * @author wanglei
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    @Autowired
    private SysMenuMapper menuMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private ISysMenuService iSysMenuService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService iSysUserService;


    /**
     * 根据用户查询系统菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuList(Long userId) {
        return selectMenuList( userId);
    }

    /**
     * 查询系统菜单列表
     *
     * @param userId 用户iD
     * @return 菜单列表
     */
    @Override
    public List<MenuVO> selectMenuListByUserId(Long userId) {
        List<SysMenu> menuList = null;
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(userId)) {
            menuList = menuMapper.selectMenuList(null,new MenuSearch()).getRecords();
        } else {
            menuList = roleMenuMapper.selectMenuListByUserId(userId);
        }
        return BeanProUtils.copyListProperties(menuList,MenuVO::new);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = roleMenuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询权限
     *
     * @param roleId 角色ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByRoleId(Long roleId) {
        List<String> perms = roleMenuMapper.selectMenuPermsByRoleId(roleId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */

    private List<SysMenu> selectMenuByUserId(Long userId) {
        List<SysMenu> menus = null;
        if (iSysUserService.isAdmin(userId)) {
            menus = menuMapper.selectMenuTreeAll();
        } else {
            menus = roleMenuMapper.selectMenuTreeByUserId(userId);
        }
        return menus;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuTreeByUserId(Long userId) {
        List<SysMenu> menus = null;
        if (iSysUserService.isAdmin(userId)) {
            menus = menuMapper.selectMenuTreeAll();
        } else {
            menus = roleMenuMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

    /**
     * 根据角色ID查询菜单树信息
     *
     * @param roleId 角色ID
     * @return 选中菜单列表
     */
    @Override
    public List<Long> selectMenuListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectRoleById(roleId);
        return roleMenuMapper.selectMenuListByRoleId(roleId, role.getMenuCheckStrictly());
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    @Override
    @Transactional
    public R insertRoleMenu(EditRoleMenu role) {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds()) {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }

        if (list.size() > 0) {
            // 删除角色与菜单关联
            roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        //关联显示
        SysRole sysRole= roleMapper.selectRoleById(role.getRoleId());
        sysRole.setMenuCheckStrictly(role.getMenuCheckStrictly());
        roleMapper.updateRole(sysRole);
        return R.ok();
    }




    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext(); ) {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                iSysMenuService.recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    @Override
    public Set<String> getPermissionCache(Long userId) {

        String key = CacheUtil.getKey(UserConstants.UserRedisKeyPrefix.PERMISSION, String.valueOf(userId));
        Set<String> urlPermission = redisCache.getCacheObject(key);
        if (urlPermission == null) {
            if (SecurityUtils.isAdmin(userId)) {
                urlPermission = menuMapper.selectMenuComponent();
            } else {
                urlPermission = roleMenuMapper.selectMenuPermsByUserIdV2(userId);
            }
            redisCache.setCacheObject(key, urlPermission, 7L, TimeUnit.DAYS);
        }
        if (urlPermission == null) {
            urlPermission = new HashSet<>();
        }
        return urlPermission;
    }

    @Override
    public void removePermissionCache(Integer userId) {
        String key = CacheUtil.getKey(UserConstants.UserRedisKeyPrefix.PERMISSION, String.valueOf(userId));
        redisCache.deleteObject(key);
    }

    @Override
    public RoleMenuTree roleMenuTreeOfSelect(Long roleId) {
        //获取当前用户的权限菜单
        List<SysMenu> menus=selectMenuByUserId(SecurityUtils.getUserId());
        //获取角色的菜单权限
        List<Long> roleMenus=selectMenuListByRoleId(roleId);

        List<TreeSelect>  selects= iSysMenuService.buildMenuTreeSelect(menus);
        RoleMenuTree tree=new RoleMenuTree();
        tree.setMenus(selects);
        tree.setCheckedKeys(roleMenus);
        return tree;
    }


}
